package com.dinadi.yidi.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.UpdateHeadImgBean;
import com.dinadi.yidi.bean.UserInfoBean;
import com.dinadi.yidi.bean.eventbus.EventUserInfo;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.UpdateHeadImgInterface;
import com.dinadi.yidi.ui.MyApplication;
import com.dinadi.yidi.ui.view.PickerView;
import com.dinadi.yidi.ui.view.SelectImage;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.PhotoUtilChange;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.StringUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;

import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2017/3/29   编辑资料
 * Time: 19:04
 */

public class EditProfileActivity extends BaseActivity {
    private static final int REQUEST_CODE_ASK_EXTRA_READ = 44;
    private View view;
    private TextView tvTitle, user_nick_name, user_name, user_sex, user_age, user_position, user_autograph;
    private CircleImageView head_img;
    private RelativeLayout edit_nickname, edit_head_img, edit_name, edit_position, edit_autograph, edit_age, edit_sex;
    private String sex, userID, token;
    List<String> yearData;
    List<String> monthData;
    List<String> dayData;
    String birth, year, month, day;
    Calendar cal;
    private UserInfoBean bean;
    private String sexString;
    private Bitmap bitmap;
    private UtilPopupWindow popupWindow, popupWindow2;

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(EditProfileActivity.this).inflate(R.layout.activity_edit_profile, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.edit_data));
        edit_head_img = (RelativeLayout) view.findViewById(R.id.edit_head_img);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        user_nick_name = (TextView) view.findViewById(R.id.user_nick_name);
        user_name = (TextView) view.findViewById(R.id.user_name);
        user_sex = (TextView) view.findViewById(R.id.user_sex);
        user_age = (TextView) view.findViewById(R.id.user_age);
        user_position = (TextView) view.findViewById(R.id.user_position);
        user_autograph = (TextView) view.findViewById(R.id.user_autograph);
        edit_nickname = (RelativeLayout) view.findViewById(R.id.edit_nickname);
        edit_name = (RelativeLayout) view.findViewById(R.id.edit_name);
        edit_position = (RelativeLayout) view.findViewById(R.id.edit_position);
        edit_autograph = (RelativeLayout) view.findViewById(R.id.edit_autograph);
        edit_age = (RelativeLayout) view.findViewById(R.id.edit_age);
        edit_sex = (RelativeLayout) view.findViewById(R.id.edit_sex);
        //注册EventBus  
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册evebtbus
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initListener() {
        registerClickListener(edit_head_img, edit_nickname, edit_name, edit_position, edit_autograph, edit_age, edit_sex);
    }

    @Override
    public void onResume() {
        super.onResume();

        String isRefresh = SharePreferencesHelper.getInstance(EditProfileActivity.this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userID = SharePreferencesHelper.getInstance(EditProfileActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(EditProfileActivity.this).getString("token");
            SharePreferencesHelper.getInstance(EditProfileActivity.this).putString("isRefresh", "no");
        }

    }

    @Override
    protected void initData() {
        /*用户ID*/
        userID = SharePreferencesHelper.getInstance(EditProfileActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(EditProfileActivity.this).getString("token");
        /*头像地址*/
        String headImg = MyApplication.getApp().getUser().getHeadImg();
        if (headImg != null) {
            if (!headImg.equals("")) {
                ImageUtils.loadImageView(EditProfileActivity.this, headImg, head_img);
            } else {
                ImageUtils.loadImageView(EditProfileActivity.this, R.drawable.me_img_default, head_img);
            }
        }
        /*昵称*/
       String nickName = MyApplication.getApp().getUser().getNickName();
        if (nickName != null) {
            user_nick_name.setText(nickName);
        } else {
            user_nick_name.setText("");
        }
        /*姓名*/
       String name = MyApplication.getApp().getUser().getUserName();
        if (name != null) {
            user_name.setText(name);
        } else {
            user_name.setText("");
        }
        /*性别*/
        sex = MyApplication.getApp().getUser().getSex();
        if (sex != null) {
            if (sex.equals("1")) {
                user_sex.setText("男");
                sexString = "男";
            } else if (sex.equals("2")) {
                user_sex.setText("女");
                sexString = "女";
            }

        } else {
            user_sex.setText("女");
            sexString = "女";
        }
        /*年龄*/
        birth = MyApplication.getApp().getUser().getAge();
        //   birth = "19300420";
        if (birth.length() < 9) {
            birth = "19900420";
            StringBuffer stringBuffer = new StringBuffer(birth);
            stringBuffer.insert(4, "-");
            stringBuffer.insert(7, "-");
            birth = stringBuffer.toString();
            user_age.setText(birth);
        } else {
            if (birth != null && !birth.equals("0")) {
                StringBuffer stringBuffer = new StringBuffer(birth);
                stringBuffer.insert(4, "-");
                stringBuffer.insert(7, "-");
                birth = stringBuffer.toString();
                user_age.setText(birth);
            }
        }

        /*职位*/
       String position = MyApplication.getApp().getUser().getBrandName();
        if (position != null) {
            user_position.setText(position);
        } else {
            user_position.setText("");
        }
        /*签名*/
       String  autograph = MyApplication.getApp().getUser().getSignature();
        if (autograph != null) {
            user_autograph.setText(autograph);
        } else {
            user_autograph.setText("");
        }
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.edit_head_img:
                /*上传头像*/
                ShowHeadImgDialog();
                break;
            case R.id.edit_nickname:
                /*修改你昵称*/
                Intent intent = new Intent(EditProfileActivity.this, EditUserDataActivity.class);
                intent.putExtra("nickName", user_nick_name.getText().toString());
                intent.putExtra("usertype", "1");
                startActivity(intent);
                break;
            case R.id.edit_name:
                /*修改姓名*/
                Intent intent2 = new Intent(EditProfileActivity.this, EditUserDataActivity.class);
                intent2.putExtra("name", user_name.getText().toString());
                intent2.putExtra("usertype", "2");
                startActivity(intent2);
                break;
            case R.id.edit_position:
                /*修改职位*/
                Intent intent3 = new Intent(EditProfileActivity.this, EditUserDataActivity.class);
                intent3.putExtra("position", user_position.getText().toString());
                intent3.putExtra("usertype", "3");
                startActivity(intent3);
                break;
            case R.id.edit_autograph:
                /*修改签名*/
                Intent intent4 = new Intent(EditProfileActivity.this, EditUserDataActivity.class);
                intent4.putExtra("autograph", user_autograph.getText().toString());
                intent4.putExtra("usertype", "4");
                startActivity(intent4);
                break;
            case R.id.edit_sex:
                /*选择性别*/
                selectSex();
                break;
            case R.id.edit_age:
                /*选择年龄*/
                selectBirth();
                break;

            default:
                break;
        }
    }

    /* 上传头像 */
    private void ShowHeadImgDialog() {

        SelectImage selectImage = new SelectImage(EditProfileActivity.this);
        selectImage.setCameraListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                    /*拍照*/
                PhotoUtilChange.takePhoto(EditProfileActivity.this, null);
            }
        });
        selectImage.setPhotoListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                PhotoUtilChange.pickPhoto(EditProfileActivity.this, null);
            }
        });
        selectImage.showAtLocation(this.findViewById(R.id.linearlayout_base), Gravity.BOTTOM, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == 1) {
                //拍照成功，开始剪切图片
              /*剪切*/
                PhotoUtilChange.onPhotoFromCamera(this, null, 50, 50);
            } else if (requestCode == 3) {

                //动态获取读写权限
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_EXTRA_READ);
                        return;
                    } else {
                        //开始上传
                        updateHeadImg();

                    }
                } else {
                    //开始上传
                    updateHeadImg();


                }


            } else if (requestCode == 2) {
                PhotoUtilChange.onPhotoFromPick(this, data.getData(), null, 50, 50);
            } else if (requestCode == REQUEST_CODE_ASK_EXTRA_READ) {
                if (Build.VERSION.SDK_INT >= 23) {
                    int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    } else {
                        Bitmap bitmap = PhotoUtilChange.getBitmap(this);
                        head_img.setImageBitmap(bitmap);
                    }
                } else {
                    Bitmap bitmap = PhotoUtilChange.getBitmap(this);
                    head_img.setImageBitmap(bitmap);
                }
            }
            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    private void updateHeadImg() {
        bitmap = PhotoUtilChange.getBitmap(EditProfileActivity.this);
        String bitmapImg = bitmaptoString(bitmap, 80);
        UpdateHeadImgBean updateBean = new UpdateHeadImgBean();
        updateBean.setUserId(userID);
        updateBean.setToken(token);
        updateBean.setFileType("jpg");
        updateBean.setFileName("temp2");
        updateBean.setFileDesc("头像上传");
        updateBean.setFileBase64Content(bitmapImg);
        UpdateHeadImgInterface updateHeadImgInterface = new UpdateHeadImgInterface(EditProfileActivity.this, httpListener2);
        updateHeadImgInterface.getInterface("15004", updateBean);

    }

    /*选择性别*/
    private void selectSex() {

        //当然是先初始化popupWindow
        popupWindow2 = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_select_1, null);
        LinearLayout layout2 = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_edit_profile, null);
        popupWindow2.setPopupWindow(EditProfileActivity.this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);

        PickerView picker_view = (PickerView) layout.findViewById(R.id.picker_view);
        final TextView btn_confirm = (TextView) layout.findViewById(R.id.btn_confirm);
        //选择性别
        List<String> data = new ArrayList<String>();
        data.add("男");
        data.add("女");

        picker_view.setData(data);
        //默认
//        sex = user_sex.getText().toString();
        picker_view.setSelected(sexString);

        picker_view.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                //选中的人群
                sexString = text;
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (sexString.equals("男")) {
                    sex = "1";
                } else {
                    sex = "2";
                }
              /*上传性别*/
                bean = new UserInfoBean();
                bean.setUserId(userID);
                bean.setToken(token);
                bean.setSex(sex);
                CommonInterface userDataEditingInterface = new CommonInterface(EditProfileActivity.this, httpListener);
                userDataEditingInterface.getInterface("11001", JSON.toJSONString(bean));


            }
        });
        TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow2.dismiss();
            }
        });

    }

    /*选择年龄*/
    private void selectBirth() {

        //当然是先初始化popupWindow
        popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_select_3, null);
        LinearLayout layout2 = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_edit_profile, null);
        popupWindow.setPopupWindow(EditProfileActivity.this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);

        //        选择出生日期
        PickerView   picker_year = (PickerView) layout.findViewById(R.id.picker_year);
        PickerView picker_month = (PickerView) layout.findViewById(R.id.picker_month);
        final PickerView picker_day = (PickerView) layout.findViewById(R.id.picker_day);
        TextView btn_confirm = (TextView) layout.findViewById(R.id.btn_confirm);
        //     birth = "1917-07-15";
        birth = user_age.getText().toString();
        //birthday.setText(birth);
        yearData = new ArrayList<>();
        monthData = new ArrayList<>();
        dayData = new ArrayList<>();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = format1.parse(birth);
            cal = Calendar.getInstance();
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        //年
        for (int i = 1900; i < c.get(Calendar.YEAR) - 4; i++) {
            yearData.add(i + "");
        }
        picker_year.setData(yearData);
        picker_year.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                year = text;
                dayData.clear();
                for (int i = 1; i < StringUtil.getDays(year, month).length + 1; i++) {
                    dayData.add(i + "");
                }
                picker_day.setData(dayData);
                if (dayData.contains(day)) {
                    picker_day.setSelected(dayData.indexOf(day));
                } else {
                    picker_day.setSelected(0);
                }
                Calendar calendar = Calendar.getInstance();
                calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
                birth = (new SimpleDateFormat("yyyy-MM-dd")).format(calendar.getTime());
                // birthday.setText(birth);
            }
        });
        picker_year.setSelected(yearData.indexOf(cal.get(Calendar.YEAR) + ""));
        year = yearData.get(yearData.indexOf(cal.get(Calendar.YEAR) + ""));
        //月
        for (int i = 1; i < 13; i++) {
            monthData.add(i + "");
        }
        picker_month.setData(monthData);
        picker_month.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                month = text;
                dayData.clear();
                for (int i = 1; i < StringUtil.getDays(year, month).length + 1; i++) {
                    dayData.add(i + "");
                }
                picker_day.setData(dayData);
                if (dayData.contains(day)) {
                    picker_day.setSelected(dayData.indexOf(day));
                } else {
                    picker_day.setSelected(0);
                }
                Calendar calendar = Calendar.getInstance();
                calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
                birth = (new SimpleDateFormat("yyyy-MM-dd")).format(calendar.getTime());
                // birthday.setText(birth);
            }
        });
        picker_month.setSelected(monthData.indexOf((cal.get(Calendar.MONTH) + 1) + ""));
        month = monthData.get(monthData.indexOf((cal.get(Calendar.MONTH) + 1) + ""));
        //日
        for (int i = 1; i < StringUtil.getDays(cal.get(Calendar.YEAR) + "", (cal.get(Calendar.MONTH) + 1) + "").length + 1; i++) {
            dayData.add(i + "");
        }
        picker_day.setData(dayData);
        picker_day.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                day = text;
                Calendar calendar = Calendar.getInstance();
                calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
                birth = (new SimpleDateFormat("yyyy-MM-dd")).format(calendar.getTime());
                // birthday.setText(birth);
            }
        });
        picker_day.setSelected(dayData.indexOf(cal.get(Calendar.DAY_OF_MONTH) + ""));
        day = dayData.get(dayData.indexOf(cal.get(Calendar.DAY_OF_MONTH) + ""));

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*上传数据*/
                bean = new UserInfoBean();
                bean.setUserId(userID);
                bean.setToken(token);
                String a = birth.replace("-", "");
                bean.setAge(birth.replace("-", ""));

                CommonInterface userDataEditingInterface = new CommonInterface(EditProfileActivity.this, httpListener3);
                userDataEditingInterface.getInterface("11001", JSON.toJSONString(bean));

            }
        });
        TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                if (sex.equals("1")) {
                    user_sex.setText("男");
                } else {
                    user_sex.setText("女");
                }

                bean.setSex(sex);
                MyApplication.getApp().getUser().setSex(sex);
                String a = bean.getHeadImg();
                EventBus.getDefault().post(new EventUserInfo(bean));
                toast("修改成功");
                popupWindow2.dismiss();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("修改失败");
        }
    };
    HttpListener httpListener3 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                popupWindow.dismiss();
                user_age.setText(birth);
                bean.setAge(birth.replace("-", ""));
                MyApplication.getApp().getUser().setAge(birth.replace("-", ""));
                //   String a=bean.getHeadImg();
                EventBus.getDefault().post(new EventUserInfo(bean));
                toast("修改成功");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("修改失败");
        }
    };
    HttpListener httpListener2 = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                head_img.setImageBitmap(bitmap);
                String imgId = JsonUtil.getFieldValue(response, "imgId");
                String imgUrl = JsonUtil.getFieldValue(response, "imgUrl");
                bean = new UserInfoBean();
                bean.setUserId(userID);
                bean.setToken(token);
                bean.setHeadImgId(imgId);
                bean.setHeadImg(imgUrl);
                CommonInterface userDataEditingInterface = new CommonInterface(EditProfileActivity.this, httpListener);
                userDataEditingInterface.getInterface("11001", JSON.toJSONString(bean));
                MyApplication.getApp().getUser().setHeadImg(imgId);
                MyApplication.getApp().getUser().setHeadImg(imgUrl);
                //    EventBus.getDefault().post(new EventUserInfo(bean));
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("上传头像失败");
        }
    };

    /**
     * 　　* 将bitmap转换成base64字符串
     * 　　*
     * 　　* @param bitmap
     * 　　* @return base64 字符串
     */
    public String bitmaptoString(Bitmap bitmap, int bitmapQuality) {
        // 将Bitmap转换成字符串
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, bitmapQuality, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    public void onEventMainThread(EventUserInfo event) {

            /*昵称*/
        String newNickName = event.getUserInfoBean().getNickName();
        if (newNickName != null) {
            user_nick_name.setText(newNickName);
        }

        /*姓名*/
        String newName = event.getUserInfoBean().getUserName();
        if (newName != null) {
            user_name.setText(newName);
        }

        /*职位*/
        String newPosition = event.getUserInfoBean().getBrandName();
        if (newPosition != null) {
            user_position.setText(newPosition);
        }
        /*签名*/
        String newAutograph = event.getUserInfoBean().getSignature();
        if (newAutograph != null) {
            user_autograph.setText(newAutograph);
        }
    }

}
